package com.bigdata.controller;/**
 * Created by Administrator on 2019/7/5 0005.
 */

import com.alibaba.fastjson.JSON;
import com.bigdata.service.mysql.JkfwUserService;
import com.bigdata.utils.ResponseUtil;
import com.bigdata.utils.ServletUtils;
import com.bigdata.model.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Administrator
 * @description 初始化入口
 * @date 2019/7/5 0005
 */
@RequestMapping("/")
@Controller
public class IndexController extends BaseController {

    @Autowired
    JkfwUserService jkfwUserService;

    @RequestMapping(value = "")
    public String index(HttpServletRequest request) {
        return "redirect:/mge/adx/bs";
    }

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        if (ServletUtils.isAjaxRequest(request)) {
            ResponseUtil.renderJson(response, JSON.toJSONString(AjaxResult.authc("未登录或登录超时，请重新登录")));
            return null;
        }
        
        return "login";
    }


    /**
     * @param request, username, password, rememberMe
     * @return com.bigdata.vo.AjaxResult
     * @Author lly
     * @Date 2019/7/12 0012
     * @Description
     */
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult postAjax(HttpServletRequest request, String username, String password, @RequestParam(name = "rememberMe", defaultValue = "false") Boolean rememberMe) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, false);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            String message = e.getMessage();
            if (e instanceof IncorrectCredentialsException) {
                message = "用户名密码不正确！";
            }
            return AjaxResult.fail(message);
        }
        AjaxResult result = AjaxResult.ok();
        result.setData(request.getContextPath() + "/mge/adx/bs");
        return result;
    }

    /**
     * @return java.lang.String
     * @Author lly
     * @Date 2019/7/12 0012
     * @Description 退出登录
     */
    @RequestMapping("/loginout")
    public String loginout(HttpServletRequest request) {
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }

}